package cn.crism.chatme.service.impl;

import cn.crism.chatme.enums.MsgSignFlagEnum;
import cn.crism.chatme.mapper.ChatMsgMapper;
import cn.crism.chatme.netty.ChatMsg;
import cn.crism.chatme.service.ChatMsgService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @CreateDate: 2018/12/29 2:54 PM
 * @Description:
 * @Author: Crism
 */
@Service
public class ChatMsgServiceImpl implements ChatMsgService {

    @Autowired
    private ChatMsgMapper chatMsgMapper;
    @Autowired
    private Sid sid;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String saveMsg(ChatMsg chatMsg) {
        cn.crism.chatme.pojo.ChatMsg msgPojo = new cn.crism.chatme.pojo.ChatMsg();
        String chatMsgId = sid.nextShort();
        msgPojo.setChatMsgId(chatMsgId);
        msgPojo.setFromUserId(chatMsg.getSenderId());
        msgPojo.setToUserId(chatMsg.getReceiverId());
        msgPojo.setCreateTime(new Date());
        msgPojo.setSignFlag(MsgSignFlagEnum.unsign.type);
        msgPojo.setMsg(chatMsg.getMsg());
        chatMsgMapper.insert(msgPojo);
        return chatMsgId;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateMsgSigned(List<String> msgIdList) {
        chatMsgMapper.updateMsgSigned(msgIdList);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<cn.crism.chatme.pojo.ChatMsg> getUnReadMsgList(String userId) {
        Example chatMsg = new Example(cn.crism.chatme.pojo.ChatMsg.class);
        Example.Criteria chatMsgCriteria = chatMsg.createCriteria();
        chatMsgCriteria.andEqualTo("signFlag",0);
        chatMsgCriteria.andEqualTo("toUserId",userId);
        return chatMsgMapper.selectByExample(chatMsg);
    }
}
